import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:image_picker/image_picker.dart';

import '../../utils/ToastUtil.dart';
import '../../utils/eventbus.dart';
import '../../utils/http.dart';

class ProfilePage extends StatefulWidget {
  ProfilePage({super.key, required this.userInfo});

  Map userInfo = {
    "avatar": "",
    "nickName": "",
  };

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  Map userInfo = {
    "avatar": "",
    "nickName": "",
  };
  final TextEditingController _nickController = TextEditingController();

  @override
  void initState() {
    super.initState();
    debugPrint("userInfo:${widget.userInfo}");
    setState(() {
      userInfo = widget.userInfo;
      _nickController.text = userInfo['nickName'];
    });
  }

  saveNick() async {
    // 获取昵称
    String nickName = _nickController.text;
    if (nickName.isEmpty) {
      return ToastUtil.showError('昵称不能为空');
    }
    // 调用保存昵称的接口
    await Http.getInstance().put('/userInfo', {
      "nickName": nickName,
    });
    // 更新用户信息
    setState(() {
      userInfo['nickName'] = _nickController.text;
      ToastUtil.showSuccess('修改成功!');
    });
    eventBus.fire(RefreshProfile());
  }

  selectAvatar() {
    showModalBottomSheet(
        context: context,
        builder: (context) {
          return Container(
              height: 200,
              child: Column(children: [
                ListTile(
                  leading: const Icon(Icons.camera_alt),
                  title: const Text('拍照'),
                  onTap: () {
                    uploadAvatar('camera');
                  },
                ),
                ListTile(
                  leading: const Icon(Icons.photo_library),
                  title: const Text('相册'),
                  onTap: () {
                    uploadAvatar('photo_library');
                  },
                )
              ]));
        });
  }

  uploadAvatar(String imageType) async {
    ImagePicker picker = ImagePicker();
    if (imageType == 'camera') {
      // 调用相机
      XFile? imageFile = await picker.pickImage(source: ImageSource.camera);
      if (imageFile != null) {
        ToastUtil.showSuccess(imageFile.path);
        uploadData(imageFile);
      }
    } else {
      // 调用相册
      XFile? imageFile = await picker.pickImage(source: ImageSource.gallery);
      uploadData(imageFile);
    }
  }

  uploadData(XFile? imageFile) async {
    try {
      // 调用上传接口
      FormData formData = FormData.fromMap({
        "file": await MultipartFile.fromFile(imageFile!.path),
        "type": "avatar",
      });
      var res = await Http.getInstance().post('/upload', formData);
      if (res['code'] != 10000) return ToastUtil.showError('上传图片失败!');
      setState(() {
        userInfo['avatar'] = res['data']['url'];
      });
    } finally {
      // Navigator.pop(context);
      context.pop();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('个人信息'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
        leading: IconButton(
          onPressed: () {
            eventBus.fire(RefreshProfile());
            // Navigator.pop(context);
            context.pop();
          },
          icon: const Icon(Icons.arrow_back),
        ),
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          SizedBox(
              height: 40,
              child: GestureDetector(
                onTap: selectAvatar,
                child: Row(
                  children: [
                    const Text('头像', style: TextStyle(fontSize: 16)),
                    const Spacer(),
                    Row(
                      children: [
                        ClipRRect(
                            borderRadius: BorderRadius.circular(50.0),
                            child: userInfo['avatar'] != '' &&
                                    userInfo['avatar'] != null
                                ? Image.network(userInfo['avatar'],
                                    width: 30, height: 30)
                                : Image.asset('images/avatar_1.jpg',
                                    width: 30, height: 30)),
                        const Icon(Icons.arrow_forward_ios, size: 12)
                      ],
                    )
                  ],
                ),
              )),
          Row(
            children: [
              const Text('昵称'),
              const Spacer(),
              Expanded(
                child: TextField(
                  controller: _nickController,
                  decoration: InputDecoration(
                      hintText: userInfo['nickName'] ?? '请输入昵称',
                      border: InputBorder.none),
                  textAlign: TextAlign.right,
                  onEditingComplete: () {
                    saveNick();
                  },
                ),
              ),
              const Icon(Icons.arrow_forward_ios, size: 12)
            ],
          )
        ],
      ),
    );
  }
}
